package com.dacd.soundanalysis.thread

import android.os.Handler
import com.dacd.soundanalysis.bean.SoundBean
import com.dacd.soundanalysis.soundhelper.SoundConstants

/**
 * 分析音频的线程
 */
class AnalysisThread(
    handler: Handler,
    compareList: List<SoundBean>,
    recordList: ArrayList<SoundBean>
) : Thread() {

    private var compareList: List<SoundBean>? = null
    private var recordList: ArrayList<SoundBean>? = null
    private var handler: Handler? = null

    init {
        this.handler = handler
        this.compareList = compareList
        this.recordList = recordList
    }

    override fun run() {
        val compareStartTime = compareList!![0].timeMillis
        val recordStartTime = recordList!![0].timeMillis//当前记录的开始时间
        recordList!!.removeAt(0)
        var startIndex = 5//子循环开始的位置
        var compareItemCount: Int = 0
        for (i in 5 until compareList!!.size) {//从第二个元素开始找匹配
            val progressTime = compareList!![i].timeMillis//目前元素距离开始的时间
            val nowFrequency = compareList!![i].frequency
            if (startIndex > (recordList!!.size - 1)) {
                break//跳出循环开始统计
            }
            for (j in startIndex until recordList!!.size) {
                val nowItemTime = recordList!![j].timeMillis//现在元素的时间
                val nowProgressTime = nowItemTime//目前元素距离开始的时间
                if((progressTime - nowProgressTime) > SoundConstants.SOUND_POSITION) {//如果距离现在元素还差100毫秒开外，那么直接跳过
                    startIndex = j + 1//以前的元素就不需要对比了
                    continue
                } else if(kotlin.math.abs(progressTime - nowProgressTime) < SoundConstants.SOUND_POSITION){//在对比范围时间之内
                    val compareFrequency = recordList!![j].frequency
                    if (kotlin.math.abs(nowFrequency - compareFrequency) < SoundConstants.SOUND_FRE_COMPARE) {//频率在200以内算作匹配
                        compareItemCount++
                        startIndex = j + 1
                        break
                    }
                } else if ((progressTime - nowProgressTime) < -SoundConstants.SOUND_POSITION) {//已经越来越远离范围了，不用再继续循环了
                    break
                }
            }
        }
        if (compareItemCount > (recordList!!.size / 2)) {
            handler!!.sendEmptyMessage(0)
        }
    }
}